package com.config;

import com.pojoVO.CommentInfoVo;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2020/4/16 0016.
 */

@Component
public class MyWebSocketHandler implements WebSocketHandler {
    private static final Map<String ,WebSocketSession> userMap=new HashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String loginUserId = (String)webSocketSession.getAttributes().get("loginUserId");
            userMap.put(loginUserId,webSocketSession);
        Set<String> userids = userMap.keySet();
        System.out.println("现在在线的用户有"+userids);
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public List<String> sendMsgToFront (final TextMessage message, CommentInfoVo type) throws  Exception{
        Iterator<Map.Entry<String ,WebSocketSession>> it=userMap.entrySet().iterator();
        List<String> idLists=new ArrayList<>();
        while (it.hasNext()){
            final Map.Entry<String ,WebSocketSession> entry=it.next();
            System.out.println(entry.getValue().isOpen());
            System.out.println(entry.getKey().equals(type.getReplyUserId().toString()));
            if(entry.getValue().isOpen()&&entry.getKey().equals(type.getReplyUserId().toString())){
                String loginUserId =(String) entry.getValue().getAttributes().get("loginUserId");
                idLists.add(loginUserId);
                System.out.println("发送评论给id="+loginUserId);
                System.out.println("发送的消息为="+message);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if(entry.getValue().isOpen()){
                                entry.getValue().sendMessage(message);
                            }
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
        return idLists;
    }
}
